from flask import Flask, g, session
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from models import db, User, Role, Permission
from auth import auth_bp
from admin import admin_bp
from blueprints.main import main_bp

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'your-secret-key'

# 初始化扩展
db.init_app(app)
migrate = Migrate(app, db)

# 注册蓝图
app.register_blueprint(auth_bp)
app.register_blueprint(admin_bp)
app.register_blueprint(main_bp)

@app.before_request
def load_user():
    if 'user_id' in session:
        g.user = User.query.get(session['user_id'])
    else:
        g.user = None

# 创建数据库表
@app.before_first_request
def create_tables():
    db.create_all()
    # 初始化角色和权限
    if not Role.query.first():
        admin_role = Role(name='admin', description='管理员')
        user_role = Role(name='user', description='普通用户')
        
        # 创建权限
        permissions = [
            Permission(name='view_dashboard', description='查看仪表板'),
            Permission(name='manage_users', description='管理用户'),
            Permission(name='manage_roles', description='管理角色'),
            Permission(name='manage_permissions', description='管理权限')
        ]
        
        # 为管理员角色分配所有权限
        admin_role.permissions = permissions
        user_role.permissions = [permissions[0]]  # 普通用户只能查看仪表板
        
        db.session.add_all([admin_role, user_role] + permissions)
        db.session.commit()
        
        # 创建默认管理员用户
        if not User.query.first():
            admin = User(username='admin')
            admin.set_password('admin123')
            admin.roles.append(admin_role)
            db.session.add(admin)
            db.session.commit()

# 添加模板全局变量
@app.context_processor
def inject_user():
    return dict(current_user=g.user)

if __name__ == '__main__':
    app.run(debug=True) 